package com.dm0858.bianmin.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.app.MyApp;
import com.dm0858.bianmin.mine.tools.LogUtils;
import com.dm0858.bianmin.mine.tools.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import butterknife.OnClick;
import cn.qqtheme.framework.util.ScreenUtils;


public class ReleaseActivity extends AppCompatActivity {
    private GridView gridview;

    private List<String> pathList = new ArrayList<String>();
    private List<String> upPathList = new ArrayList<String>();

    private LinearLayout topView;
    private ListView releaseList;
    private int height;
    private int typeInt;
    private GridAdapter gridAdapter;
    private ReleaseAdapter adapter;
    private boolean isOneHeight = true;

    private List<String> uploadPhoto = new ArrayList<String>();


    private ImageView iv_back;
    int viewWidth;
    int viewHeight;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release);
        CacheUtils.setReleaseContent(this,"");
        CacheUtils.setPhotoPath(this,"");
        typeInt = getIntent().getIntExtra("typeInt",0);
        LayoutInflater inflater = LayoutInflater.from(this);
        ///所需的列表
        releaseList = findViewById(R.id.releaseList);
        ///列表顶部试图
        topView = (LinearLayout) inflater.inflate(R.layout.gridphoto_item, null);
        ///顶部试图里的九宫格
        gridview = topView.findViewById(R.id.gridview);
        ///获取图片id的bitmap

        iv_back = findViewById(R.id.iv_backfabu);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        pathList.add("-1");

        int screenWidth = ScreenUtils.widthPixels(this);
        int screenHeight = ScreenUtils.heightPixels(this);
//每个子项占宽度的三分之一，高度是宽屏的分七分，再占三分中的二分之一,还需要减去下面toolbar
        viewWidth = screenWidth/3 - 20;
        viewHeight = screenHeight*3/(2*8) - 20;
        ///adapter
        gridAdapter = new GridAdapter(this,R.layout.photoitem,pathList,viewWidth,viewHeight,this);
        //gridview = (GridView) findViewById(R.id.gridview);


        gridview.setAdapter(gridAdapter);



        initProgressDialog();

        releaseList.addHeaderView(topView);//添加头部
        final String [] release;


        if (typeInt == 10) {
            release = new String[]{"标题"
                    , "地区"
                    , "详细地址"
                    , "小区名称"
                    , "户型"
                    , "面积"
                    , "价格"
                    , "联系人"
                    , "联系电话"
                    , "房源描述"};

            adapter = new ReleaseAdapter(this, R.layout.release_item, release,this);

        }else if (typeInt == 17){
            release = new String[]{"标题"
                    , "车型"
                    , "里程"
                    , "首次上牌"
                    , "排量+变速箱"
                    , "价格"
                    , "看车地址"
                    , "详细地址"
                    , "联系人"
                    , "联系电话"
                    , "车辆描述"};
            adapter = new ReleaseAdapter(this, R.layout.release_item, release,this);

        }else {
            release = new String[]{"标题"
                    , "身份信息"
                    , "备案证明"
                    , "地址"
                    , "详细地址"
                    , "联系人"
                    , "联系电话"
                    , "内容"};
            adapter = new ReleaseAdapter(this, R.layout.release_item, release,this);
        }

        final int isArrs = release.length;

        releaseList.setAdapter(adapter);


        adapter.setToggleClickListener(new ReleaseAdapter.OnToggleClickListener() {
            @Override
            public void onDoClick() {
                hideKeyboard();
                if (pathList.size() <= 1) {
                    //请选择照片
                    Toast.makeText(ReleaseActivity.this, "请选择照片",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                List<ReleaseBean> releaseBeans = getReleaseBean();
                if (releaseBeans == null || releaseBeans.size() != isArrs) {
                    //有数据没写
                    Toast.makeText(ReleaseActivity.this, "请将表格填写完整",
                    Toast.LENGTH_SHORT).show();
                    return;
                }

                uploadPhoto = new ArrayList<String>();
                i = 0;
                progressDialog.setMessage("0% 正在上传...请稍后");



                new Thread(new Runnable(){
                    @Override
                    public void run() {
                        //在这里做耗时操作.
                        upload();
                    }
                }).start();

                progressDialog.show();

            }
        });

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                if (!(pathList.get(position).equals("-1"))) {
                    //是否撤销该照片


                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            ReleaseActivity.this);
                    final Dialog dialog = new Dialog(ReleaseActivity.this);
                    builder.setTitle("");
                    builder.setMessage("是否撤销该照片？");
                    builder.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface arg0, int arg1) {

                                    pathList.remove(position);
                                    upPathList.remove(position);
                                    if (pathList.size() == 5 && !(pathList.get(0).equals("-1"))) {//说明已经选满了又删除了一张
                                        //重新增加
                                        pathList.add(0,"-1");
                                    }
                                    gridAdapter.notifyDataSetChanged();

                                    setGridViewHeight();

                                    dialog.dismiss();
                                }
                            });
                    builder.setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface arg0, int arg1) {
                                    dialog.dismiss();
                                }
                            });
                    builder.create().show();
                }else {
                    goPicture();
                }

            }
        });

    }



    private void hideKeyboard() {

        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm.isActive() && this.getCurrentFocus() != null) {

            if (this.getCurrentFocus().getWindowToken() != null) {

                imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

            }

        }

    }


    private static final int REQUEST_CODE_CHOOSE = 10086;//定义请求码常量



    private void goPicture(){
        //动态申请存储权限
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                ) {
            Toast.makeText(this, "无权限，请手动开启拍照存储权限",
                    Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, READ_PHONE_STATE);
            return;
        }
        // 进入相册
        int index = 7 - pathList.size();
        Matisse.from(ReleaseActivity.this)
                .choose(MimeType.ofImage(), false) // 选择 mime 的类型
                .countable(true)
                .capture(true)
                .captureStrategy(
                        new CaptureStrategy(true, "com.bmshfw.fileprovider"))
                .maxSelectable(index) // 图片选择的最多数量
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new PicassoEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码

    }
    List<String> mSelected;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE) {
                    if (data == null) {
                        return;
                    }

                    mSelected = Matisse.obtainPathResult(data);
                    Log.d("Matisse", "mSelected: " + mSelected);
            progressDialogTwo.show();
            new Thread(new Runnable(){
                @Override
                public void run() {
                    //在这里做耗时操作.


                    for (int i = 0; i < mSelected.size();i++) {

                        pathList.add(amendRotatePhoto(mSelected.get(i),viewWidth,viewHeight,i));
                        upPathList.add(mSelected.get(i));
                    }
                    if (pathList.size() > 6) {
                        //把增加照片的图片去掉
                        pathList.remove(0);

                    }


                    ReleaseActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            gridAdapter.notifyDataSetChanged();

                            setGridViewHeight();
                            progressDialogTwo.dismiss();
                        }
                    });

                }
            }).start();





        }

    }
    ///list转String
    public  String listToString(List<String> list){
        if(list==null){
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean first = true;
        //第一个前面不拼接","
        for(String string :list) {
            if(first) {
                first=false;
            }else{
                result.append(",");
            }
            result.append(string);
        }
        return result.toString();
    }

    ///动态获取头部高度
    public void setGridViewHeight() {
        // 获取gridview的adapter
        if (gridAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int numColumns= gridview.getNumColumns(); //5
        int totalHeight = 0;
        // 计算每一列的高度之和
        for (int i = 0; i < gridAdapter.getCount(); i += numColumns) {
            // 获取gridview的每一个item

            View listItem = gridAdapter.getView(i, null, gridview);
            listItem.measure(0, 0);
            if (isOneHeight) {
                isOneHeight = false;
                height = topView.getHeight();
                // 获取item的高度和

            }
            ///这里去获得所需高度
            totalHeight += height;

        }
        // 获取gridview的布局参数
        ViewGroup.LayoutParams params = gridview.getLayoutParams();
        ViewGroup.LayoutParams paramsLinear = topView.getLayoutParams();;
        params.height = totalHeight;
        paramsLinear.height = totalHeight;
        gridview.setLayoutParams(params);
        topView.setLayoutParams(paramsLinear);


    }







    ///上传------------------







    private List<String> stringToList(String strs){
        String str[] = strs.split(",");
        return Arrays.asList(str);
    }


    /**
     * 压缩图片（质量压缩）
     * @param bitmap
     */
    public File compressImage(Bitmap bitmap) {
        int abc = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 50;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
            abc++;
            Log.v("------------------", "" + abc);
        }
        File file = new File(Environment.getExternalStorageDirectory(),"photo"+i+".jpeg");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (i >= upPathList.size() - 1){
                    progressDialog.setMessage( "99% 正在上传...请稍后");

                }else {
                    int p = 100 / upPathList.size();
                    progressDialog.setMessage( (i+1) * p + "% 正在上传...请稍后");
                }
            }
        });
        return file;
    }

    /**
     * 上传文件到服务器
     */
    protected void upload() {
        if (i >= upPathList.size()){
            //上传数据完成了。
            if (uploadPhoto.size() != upPathList.size()) {
                //图片上传出问题了。
                progressDialog.dismiss();
                Toast.makeText(ReleaseActivity.this, "上传失败",
                        Toast.LENGTH_SHORT).show();
                progressDialog.setMessage("0% 正在上传...请稍后");
                return;
            }
            //这里作上传剩余数据的工作

            lastUpload();

            return;
        }

        // 取得图片旋转角度
        int angle = readPictureDegree(upPathList.get(i));
        Bitmap bitmap = BitmapFactory.decodeFile(upPathList.get(i));
        bitmap = rotaingImageView(angle,bitmap);
        AjaxParams params = new AjaxParams();
        try {
            params.put("file", compressImage(bitmap));


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(ReleaseActivity.this, "上传失败",
                    Toast.LENGTH_SHORT).show();
            return;
        }



        FinalHttp fh = new FinalHttp();
        fh.post("http://bmshfw.net/phpapi/bmahoutai/uploadone.php", params, new AjaxCallBack(){
                @Override
            public void onLoading(long count, long current) {

                Log.v("dddddd","正在上传");

            }

            @Override
            public void onSuccess(Object o) {//http://bmshfw.net/phpapi/bmahoutai/uploadone.phpupload\/larger\/ddd7ba4a8e5bdc262f854ea72304a8dephoto0.jpeg
                super.onSuccess(o);
                Gson gson = new Gson();


                try {

                    JSONObject json = new JSONObject(o.toString());
                    int code = 0;
                    code = json.getInt("code");
                    if (code == 200) {
                        String url = json.getJSONObject("data").getString("url");
                        uploadPhoto.add(url);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }



                i++;

                new Thread(new Runnable(){
                    @Override
                    public void run() {
                        //在这里做耗时操作.
                        upload();
                    }
                }).start();
                }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                progressDialog.dismiss();
                Toast.makeText(ReleaseActivity.this, "上传失败",
                        Toast.LENGTH_SHORT).show();
                Log.v("dabadbd","上传NO");
                progressDialog.setMessage("0% 正在上传...请稍后");

            }
        });

    }


    private void lastUpload() {
        //先拿出数据

        final List<ReleaseBean> releaseBeans = getReleaseBean();
        final HashMap<String, String> releaseMap = new HashMap<String, String>();
        for (int i = 0;i < releaseBeans.size(); i++) {
            ReleaseBean releaseBean = releaseBeans.get(i);
            releaseMap.put(releaseBean.getTitle(),releaseBean.getContent());
        }

        String photoPath = "";
        for (int i = 0; i < uploadPhoto.size(); i++) {
            if (i == 0) {
                photoPath = uploadPhoto.get(i);
            }else {
                photoPath += "," + uploadPhoto.get(i);
            }

        }
        AjaxParams params = new AjaxParams();
        String city = CacheUtils.getDriverCity(this);
        String latlon =  CacheUtils.getDriverLon(this) + "," + CacheUtils.getDriverLat(this);
        if (typeInt == 10) {
            //房屋
            params.put("classid", "9");

            params.put("title", releaseMap.get("标题"));
            params.put("call", releaseMap.get("联系电话"));
            params.put("username", releaseMap.get("联系人"));
            params.put("address", releaseMap.get("地区") + releaseMap.get("详细地址"));
            params.put("content", releaseMap.get("房源描述"));
            params.put("zuobiao",latlon);
            params.put("city", city);
            params.put("state", "1");
            params.put("xiaoqu", releaseMap.get("小区名称"));
            params.put("huxing", releaseMap.get("户型"));
            params.put("mianji", releaseMap.get("面积"));
            params.put("jiage", releaseMap.get("价格"));
            params.put("msgpic", photoPath);


        }else if (typeInt == 17) {
            //汽车
            params.put("classid", "34");

            params.put("title", releaseMap.get("标题"));
            params.put("call", releaseMap.get("联系电话"));
            params.put("username", releaseMap.get("联系人"));
            params.put("address", releaseMap.get("看车地址") + releaseMap.get("详细地址"));
            params.put("zuobiao", latlon);
            params.put("city", city);
            params.put("state", "1");
            params.put("chengxing", releaseMap.get("车型"));
            params.put("licheng", releaseMap.get("里程"));
            params.put("shangpai", releaseMap.get("首次上牌"));
            params.put("pailiang", releaseMap.get("排量+变速箱"));
            params.put("content", releaseMap.get("车辆描述"));
            params.put("jiage", releaseMap.get("价格"));
            params.put("msgpic", photoPath);

        }else {
            //其他
            String[] titles = { "开锁换锁","五金建材","家电维修",
                    "电脑维修","燃具维修","管道疏通",
                    "水电维修","卷门维修","搬家服务",
                    "家政服务","租房买房","宠物医疗",
                    "家装维修","汽车快修","同城跑腿",
                    "生活资讯","教育培训",
                    "二手汽车","平安代驾","送桶装水",
                    "药店医疗","用餐住宿","婚庆摄影","美容健身","本地特产","衣鞋定制","家电灯饰","批发采购","超市百货","旅游购物街","生活万花筒","玩转城市","车辆服务"};
            List<IndustryAll> industryAlls = getIndustryAlls();
            String classid = "0";
            for (int i = 0; i < industryAlls.size();i++) {
                if (industryAlls.get(i).getName().equals(titles[typeInt]))
                {
                    classid = industryAlls.get(i).getId();
                }
            }
            params.put("classid", classid);
            params.put("title", releaseMap.get("标题"));
            params.put("call", releaseMap.get("联系电话"));
            params.put("username", releaseMap.get("联系人"));
            params.put("address", releaseMap.get("地址") + releaseMap.get("详细地址"));
            params.put("content", releaseMap.get("内容"));
            params.put("zuobiao", latlon);
            params.put("city", city);
            params.put("state", "1");
            params.put("shengfen", releaseMap.get("身份信息"));
            params.put("beian", releaseMap.get("备案证明"));
            params.put("msgpic", photoPath);

        }


        params.put("userid", MyApp.userid);
        LogUtils.d(JSON.toJSONString(params));
        FinalHttp fh = new FinalHttp();
        fh.post("http://bmshfw.net/phpapi/info.php?func=submitMsg", params, new AjaxCallBack(){


            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                progressDialog.dismiss();
                finish();
                Toast.makeText(ReleaseActivity.this, "上传成功",
                        Toast.LENGTH_SHORT).show();
                Log.v("dasddd","上传完成" + o.toString());
                progressDialog.setMessage("0% 正在上传...请稍后");

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                progressDialog.dismiss();
                Toast.makeText(ReleaseActivity.this, "上传失败",
                        Toast.LENGTH_SHORT).show();
                Log.v("dabadbd","上传NO");
                progressDialog.setMessage("0% 正在上传...请稍后");

            }
        });
    }

    /***
     *  把StringJson转换为list类型
     */
    public <IndustryAll> List<com.dm0858.bianmin.ui.activity.IndustryAll> getIndustryAlls() {
        List<com.dm0858.bianmin.ui.activity.IndustryAll> datalist=new ArrayList<com.dm0858.bianmin.ui.activity.IndustryAll>();
        String  industryAllStr = CacheUtils.getIndustry(ReleaseActivity.this);

        if (null == industryAllStr) {
            return datalist;
        }
        Gson gson = new Gson();
        datalist = gson.fromJson(industryAllStr, new TypeToken<List<com.dm0858.bianmin.ui.activity.IndustryAll>>() {
        }.getType());
        return datalist;

    }

    /***
     *  把StringJson转换为list类型
     */
    public <ReleaseBean> List<com.dm0858.bianmin.ui.activity.ReleaseBean> getReleaseBean() {
        List<com.dm0858.bianmin.ui.activity.ReleaseBean> datalist=new ArrayList<com.dm0858.bianmin.ui.activity.ReleaseBean>();
        String strJson = CacheUtils.getReleaseContent(this);
        if (null == strJson || strJson.equals("")) {
            return datalist;
        }
        Gson gson = new Gson();
        datalist = gson.fromJson(strJson, new TypeToken<List<com.dm0858.bianmin.ui.activity.ReleaseBean>>() {
        }.getType());
        return datalist;

    }

    private int i = 0;
    private ProgressDialog progressDialog;
    private ProgressDialog progressDialogTwo;
    private void initProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setIndeterminate(false);//循环滚动
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("0% 正在上传...请稍后");
        progressDialog.setCancelable(false);//false不能取消显示，true可以取消显示
        progressDialogTwo = new ProgressDialog(this);
        progressDialogTwo.setIndeterminate(false);//循环滚动
        progressDialogTwo.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialogTwo.setMessage("正在加载中...");
        progressDialogTwo.setCancelable(false);//false不能取消显示，true可以取消显示
    }

    private static final int READ_PHONE_STATE =10110;

    public void showContacts(){

    }




    /**
     * @param bitmap 对象
     * @param w 要缩放的宽度
     * @param h 要缩放的高度
     * @return newBmp 新 Bitmap对象
     */
    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newBmp;
    }


    /**
     * 处理旋转后的图片
     * @param path 原图路径
     * @return 返回修复完毕后的图片路径
     */
    public String amendRotatePhoto(String path,int w,int h,int index) {

        // 取得图片旋转角度
        int angle = readPictureDegree(path);


        // 把原图压缩后得到Bitmap对象
        Bitmap bmp = zoomBitmap(BitmapFactory.decodeFile(path),w,h);

        // 修复图片被旋转的角度
        Bitmap bitmap = rotaingImageView(angle, bmp);


        return savePhotoToSD(bitmap,this,index);
    }

    /**
     * 读取照片旋转角度
     *
     * @param path 照片路径
     * @return 角度
     */
    public  int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    /**
     * 旋转图片
     * @param angle 被旋转角度
     * @param bitmap 图片对象
     * @return 旋转后的图片
     */
    public  Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        return returnBm;
    }


    /**
     * 保存Bitmap图片在SD卡中
     * 如果没有SD卡则存在手机中
     *
     * @param mbitmap 需要保存的Bitmap图片
     * @return 保存成功时返回图片的路径，失败时返回null
     */
    public  String savePhotoToSD(Bitmap mbitmap, Context context,int index) {
        FileOutputStream outStream = null;
        String fileName = getPhotoFileName(context,index);
        try {
            outStream = new FileOutputStream(fileName);
            // 把数据写入文件，100表示不压缩
            mbitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (outStream != null) {
                    // 记得要关闭流！
                    outStream.close();
                }
                if (mbitmap != null) {
                    mbitmap.recycle();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 存放拍摄图片的文件夹
     */
    private  final String FILES_NAME = "/MyPhoto";
    /**
     * 获取的时间格式
     */
    public  final String TIME_STYLE = "yyyyMMddHHmmss";
    /**
     * 图片种类
     */
    public  final String IMAGE_TYPE = ".png";


    /**
     * 获取手机可存储路径
     *
     * @param context 上下文
     * @return 手机可存储路径
     */
    private  String getPhoneRootPath(Context context) {
        // 是否有SD卡
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || !Environment.isExternalStorageRemovable()) {
            // 获取SD卡根目录
            return context.getExternalCacheDir().getPath();
        } else {
            // 获取apk包下的缓存路径
            return context.getCacheDir().getPath();
        }
    }

    /**
     * 使用当前系统时间作为上传图片的名称
     *
     * @return 存储的根路径+图片名称
     */
    public  String getPhotoFileName(Context context,int index) {
        File file = new File(getPhoneRootPath(context) + FILES_NAME);
        // 判断文件是否已经存在，不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        // 设置图片文件名称
        SimpleDateFormat format = new SimpleDateFormat(TIME_STYLE, Locale.getDefault());
        Date date = new Date(System.currentTimeMillis());
        String time = format.format(date);
        String photoName = "/" + time + index + IMAGE_TYPE;
        return file + photoName;
    }



}






